package org.apache.lucene.index;

import java.io.IOException;

import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.RAMOutputStream;

/**
 * Can be reused by calling reset.  Add docs, call finish
 *
 */
public class TagBlockWriter implements TagWriteable {
  private RAMOutputStream indexOutput;
  private RAMOutputStream skipOutput;
  private TagBlockSkipListWriter skipListWriter;
  private int skipInterval;
  int lastDoc = 0;
  int df = 0;

  public TagBlockWriter(int skipInterval, int maxSkipLevels, int docCount) {
    this.indexOutput = new RAMOutputStream();
    this.skipOutput = new RAMOutputStream();
    this.skipListWriter = new TagBlockSkipListWriter(skipInterval, maxSkipLevels, docCount, indexOutput);
    this.skipInterval = skipInterval;
  }
  
  public int getDocFreq() {
    return df;
  }
  
  public void add(int doc) throws IOException {
    if ((++df % skipInterval) == 0) {
      skipListWriter.setSkipData(lastDoc);
      skipListWriter.bufferSkip(df);
    }
    final int newDocCode = (doc - lastDoc) << 1;
    lastDoc = doc;
    indexOutput.writeVInt(newDocCode | 1);
  }
  
  public void write(IndexOutput output) throws IOException {
    skipListWriter.writeSkip(skipOutput);
    output.writeVInt((int)skipOutput.length());
    indexOutput.writeTo(output);
    skipOutput.writeTo(output);
  }
  
  //public void finish() throws IOException {
  //  skipListWriter.writeSkip(skipOutput);
  //}

  public void reset() {
    indexOutput.reset();
    skipOutput.reset();
    skipListWriter.resetSkip();
  }
  
  public int getSize() {
    return getDocsSize() + getSkipSize();
  }
  
  public int getDocsSize() {
    return (int)indexOutput.length();
  }

  public int getSkipSize() {
    return (int)skipOutput.length();
  }
}
